﻿using System;
using System.Linq;
using System.Web;
using Altairis.FluffyCloud.Data;

namespace Altairis.FluffyCloud.WebCore {

    public static class ExtensionMethods {
        private const string CURRENT_USER_KEY = "Altairis.FluffyCloud.WebCore.CurrentUser";
        private const string TZID = "Central Europe Standard Time";

        public static User GetUserData(this HttpContext context) {
            if (!context.Request.IsAuthenticated) return null;
            var userData = context.Items[CURRENT_USER_KEY] as User;
            if (userData == null) {
                using (var dc = new FluffyDbContext()) {
                    userData = dc.Users.Single(x => x.UserName.Equals(context.User.Identity.Name));
                    userData.DateLastActivity = DateTime.UtcNow;
                    dc.SaveChanges();
                }
            }
            return userData;
        }

        public static string ToLocalDisplayFormat(this DateTimeOffset dt) {
            var dtConverted = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, TZID);
            var todayConverted = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, TZID).Date;

            var dayDelta = (int)dtConverted.Date.Subtract(todayConverted).TotalDays;

            if (dayDelta == -1) {
                // Yesterday
                return string.Format("včera, {0:HH:mm}", dtConverted);
            }
            else if (dayDelta == 0) {
                // Today
                return string.Format("dnes, {0:HH:mm}", dtConverted);
            }
            else if (dayDelta == 1) {
                // Tomorrow
                return string.Format("zítra, {0:HH:mm}", dtConverted);
            }
            else {
                // Sometime else
                return dtConverted.ToString("dd. MM. yyyy HH:mm");
            }
        }
    }
}